package com.bw.home.viewmodel

import androidx.lifecycle.viewModelScope
import com.bw.home.intent.CommentIntent
import com.bw.home.service.CommentService
import com.bw.home.state.CommentState
import com.bw.lib_mvi.viewmodel.BaseViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.launch

class CommentViewModel : BaseViewModel<CommentIntent>() {
    private val service: CommentService by lazy { CommentService() }

    //可改变的
    private val _state = MutableStateFlow<CommentState>(CommentState.init)

    //可观察的
    val state: StateFlow<CommentState>
        get() = _state

    override fun handlerIntent() {
        viewModelScope.launch {
            intents.consumeAsFlow().collect {
                when (it) {

                    is CommentIntent.getCommentIntent -> {
                        doComment(it)
                    }

                    is CommentIntent.publishComment -> {
                        doPublishComment(it)
                    }

                    else -> {}
                }
            }
        }

    }

    private fun doPublishComment(it: CommentIntent.publishComment) {
        viewModelScope.launch(Dispatchers.IO) {
            val data = service.publishComment(it.entity)
            if (data.code == 0) {
                _state.value = CommentState.publishComment(data.data)
            } else {
                _state.value = CommentState.Failed
            }
        }
    }

    private fun doComment(it: CommentIntent.getCommentIntent) {
        viewModelScope.launch(Dispatchers.IO) {
            val data = service.getComment(it.type, it.id)
            if (data.code == 0) {
                _state.value = CommentState.getCommentState(data.data)
            } else {
                _state.value = CommentState.Failed
            }
        }
    }
}